(function () {
    let userAgent = function () {
        let ua = navigator.userAgent.toLowerCase();
        return {
            isWebkit: /webkit|khtml/.test(ua),
            isOpera: ua.indexOf('opera') > -1,
            isFirefox: ua.indexOf('firefox') > -1,
            isIE6: ua.indexOf('msie 6') > -1,
            isIE7: ua.indexOf('msie 7') > -1,
            isIE8: ua.indexOf('msie 8') > -1,
            isIE9: ua.indexOf('msie 9') > -1
        }
    }
    window.mousewheel = function () {
    }
    mousewheel.prototype.init = function (el, fn, capture) {
        var type = (userAgent().isFirefox) ? "DOMMouseScroll" : "mousewheel";
        if (window.addEventListener) {
            return function () {
                el.addEventListener(type, fn, capture);
            }
        } else if (window.attachEvent) {
            return function () {
                el.attachEvent("on" + type, fn);
            }
        }
    }
    mousewheel.prototype.stopEvent = function (event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        } else {
            event.cancelBubble = true;
        }
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
    }
    mousewheel.prototype.wheelevent = function (ele, fn) {
        var ev, _this = this, delta = 0;
        _this.init(ele, function (e) {
            ev = window.event || e;
            _this.stopEvent(ev);
            delta = ev.wheelDelta ? (ev.wheelDelta / 120) : (-ev.detail / 3);
            try {
                fn(delta);
            } catch (er) {
                return;
            }
        }, false)();
    }
    mousewheel.prototype.zoomIn = function (ele, fn) {
        this.wheelevent(ele, function (value) {
            if (value > 0) {
                fn(value);
                return;
            }
        });
    }
    mousewheel.prototype.zoomOut = function (ele, fn) {
        this.wheelevent(ele, function (value) {
            if (value < 0) {
                fn(value);
                return;
            }
        });
    }
})();
(function () {
    let params = {image: new Image(), mouseX: 0, mouseY: 0, dragable: false, upload_file: null}
    let cut = {}
    cut.trim = function (str) {
        return str.replace(/\s+/g, "");
    }
    cut.empty = function (v) {
        switch (typeof v) {
            case 'undefined':
                return true;
            case 'string':
                if (this.trim(v).length == 0) {
                    return true;
                }
                break;
            case 'boolean':
                if (!v) {
                    return true;
                }
                break;
            case 'number':
                if (0 === v) {
                    return true;
                }
                break;
            case 'object':
                if (null === v) {
                    return true;
                }
                if (undefined !== v.length && v.length == 0) {
                    return true;
                }
                for (var k in v) {
                    return false;
                }
                return true;
                break;
        }
        return false;
    }
    cut.init = function () {
        let selectBtn = document.querySelector("#selectBtn");
        let cutBtn = document.querySelector("#cutBtn");
        let uploadBtn = document.querySelector("#uploadBtn");
        let files = document.createElement("input");
        files.type = "file";
        files.name = "file";
        selectBtn.onclick = function () {
            files.click();
        }
        cutBtn.onclick = function () {

            if (cut.empty(files.value)) {
                layer.msg("请选择或拖拽要裁剪的图片！");
            } else {
                let img = cut.drawImg();
                if (cut.empty(img)) {
                    layer.msg("裁剪不正确！");
                } else {
                    document.querySelector(".file-name").innerHTML = "<img src='" + img + "' style='width: 100%;'>";
                }
            }
        }
        uploadBtn.onclick = function () {
            cut.upload(params.upload_file);
        }
        files.onchange = function () {
            if (!cut.empty(this.files[0])) {
                if (this.files[0].type.indexOf("image") === -1) {
                    layer.msg("请选择图片文件");
                } else {
                    let reader = new FileReader();
                    let file = this.files[0];
                    reader.onload = function (e) {
                        cut.create(file, e.target.result);
                    }
                    reader.readAsDataURL(this.files[0]);
                }
            }
        }
        cut.events();
    }
    //ajax 传入服务器
    cut.upload = function (file) {
        if (this.empty(file)) {
            layer.msg("请先裁剪图片");
        } else {
            //根据自己的情况上传
            layer.msg("go")
            let ajax = new XMLHttpRequest();//创建一个ajax对象
            let url = "http://localhost/user/up";//上传图片地址
            let fd = new FormData();
            ajax.open("POST", url, true);//连接服务器
            fd.append("cutfile", file);
            ajax.send(fd);//发送数据
            ajax.onreadystatechange = function () {//接收返回
                if (ajax.readyState == 4) {//读取完成
                    if (ajax.status == 200) {//读取成功

                        let r = JSON.parse(ajax.responseText)
                        console.log(r)
                        if (r.code == 1) {
                            layer.msg("图片上传成功，待审核");
                        }
                    } else {
                        layer.msg("失败" + ajax.status);
                    }
                }
            };
            return;
        }
    }
    cut.create = function (file, _src) {
        params.image.src = _src;
        layer.msg('读取图片中', {icon: 16, shade: 0.01, time: 100});
        setTimeout(function () {
            //图片名称
            let file_name = file.name;
            //把文件大小字转换为kb并保留两位小数
            let file_size = ((file.size) / 1024).toFixed(2);
            let receivedEle = document.querySelector("#TzReceived");
            let imgWidth = parseInt(params.image.width);
            let imgHeight = parseInt(params.image.height);
            receivedEle.style.backgroundImage = "url(" + _src + ")";
            receivedEle.style.backgroundSize = imgWidth + "px " + imgHeight + "px";
            receivedEle.style.backgroundRepeat = "no-repeat";
            let file_mes = "<p>文件名：>" + file_name + "</p><p>文件大小：" + file_size + "KB</p>";
            layer.tips(file_mes, '.tz-main', {
                tips: [2, '#169af3'] //还可配置颜色
            });
        }, 50);
    }
    cut.drawImg = function () {
        let receivedEle = document.querySelector("#TzReceived");
        let width = document.querySelector(".cut-box").clientWidth + 3;
        let height = document.querySelector(".cut-box").clientHeight + 3;
        let dx1 = 0, dy1 = 0;
        if (!cut.empty(receivedEle.style.backgroundPosition)) {
            let dim = receivedEle.style.backgroundPosition.split(' ');
            dx1 = parseInt(dim[0]) - receivedEle.clientWidth / 2;
            dy1 = parseInt(dim[1]) - receivedEle.clientHeight / 2;
        }
        let dx = dx1 + width / 2;
        let dy = dy1 + height / 2;
        if (dx === 100 && dy === 100) {
            return
        }
        let size = receivedEle.style.backgroundSize.split(' ');
        let dw = parseInt(size[0]);//获取背景大小的宽度
        let dh = parseInt(size[1]);//获取背景大小的高度
        let sw = parseInt(params.image.width);//获取创建图片的宽度
        let sh = parseInt(params.image.height);//获取创建图片的高度
        let canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        let context = canvas.getContext("2d");
        //参数一次为规定要使用的图像，开始剪切的 x 坐标位置，开始剪切的 y 坐标位置，被剪切图像的宽度，被剪切图像的高度，在画布上放置图像的 x 坐标位置和y 坐标位置,要使用的图像的宽度和高度。
        context.drawImage(params.image, -120, 0, sw, sh, dx, dy, dw, dh);
        let dataURL = canvas.toDataURL('image/png');
        params.upload_file = cut.toBlob(dataURL);
        return dataURL;
    }
    cut.toBlob = function (url) {
        let arr = url.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type: mime});

    }
    cut.events = function () {
        let tz_received = document.getElementById('TzReceived');
        //拖进阻止默认
        tz_received.addEventListener('dragenter', function (e) {
            e.preventDefault();
        }, false);
        //拖离阻止默认
        tz_received.addEventListener('dragleave', function (e) {
        }, false);
        //拖来拖去阻止默认
        tz_received.addEventListener('dragover', function (e) {
            e.preventDefault();
        }, false);
        //拖进扔下阻止默认
        tz_received.addEventListener('drop', function (e) {
            e.preventDefault();
            var files = e.target.files || e.dataTransfer.files;
            cut.drop(files);
        }, false);
        tz_received.addEventListener("mousedown", function (e) {
            e.stopImmediatePropagation();
            params.dragable = true;
            params.mouseX = e.clientX;
            params.mouseY = e.clientY;
        });
        tz_received.addEventListener("mousemove", function (e) {
            e.stopImmediatePropagation();
            if (params.dragable) {
                let bgX, bgY
                let x = e.clientX - params.mouseX;
                let y = e.clientY - params.mouseY;
                let receivedEle = document.querySelector("#TzReceived");
                if (!cut.empty(receivedEle.style.backgroundPosition)) {
                    let bg = receivedEle.style.backgroundPosition.split(" ");
                    bgX = x + parseInt(bg[0]);
                    bgY = y + parseInt(bg[1]);
                } else {
                    bgX = x;
                    bgY = y
                }
                params.mouseX = e.clientX;
                params.mouseY = e.clientY;
                receivedEle.style.backgroundPosition = bgX + 'px ' + bgY + 'px';
            }
        });
        window.addEventListener("mouseup", function (e) {
            e.stopImmediatePropagation();
            params.dragable = false;
        });
        new mousewheel().zoomIn(document.querySelector(".tz-received"), function (value) {
            //放大
            designImageSize("big");
        }, false);
        new mousewheel().zoomOut(document.querySelector(".tz-received"), function (value) {
            //缩小
            designImageSize("small");
        }, false);

        function designImageSize(type) {
            let receivedEle = document.querySelector("#TzReceived");
            let size = receivedEle.style.backgroundSize.split(" ");
            let width = parseInt(size[0]);
            let height = parseInt(size[1]);
            if (type === "big") {
                width = width + (width / 10);
                height = height + (height / 10);
            } else {
                width = width - (width / 10);
                height = height - (height / 10);
            }
            receivedEle.style.backgroundSize = width + "px " + height + "px";
        }
    }
    cut.drop = function (files) {
        //限制只能拖拽一个图片文件
        if (files.length == 0) {
            layer.msg("请选择要拖拽文件");
        } else if (files[0].type.indexOf("image") == -1) {
            layer.msg("请选择图片文件拖拽");
        } else if (files.length > 1) {
            layer.msg("只能拖拽一个文件");
        } else {
            cut.view(files[0]);
        }
    }
    cut.view = function (file) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var imgsrc = e.target.result; //获取图片地址
            cut.create(file, imgsrc);
        }
        reader.readAsDataURL(file);
    }
    cut.init();
    layer.msg("图片可以从文件夹拖拽哦！")
})();